package com.example.test.util;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class Server {
    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(1,1,60L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1));
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(9999);
        System.out.println("server is running...");
        for (; ; ) {
            Socket socket = ss.accept();
            if (executor.getQueue().size() >= 1) {
                System.out.println("当前连接请求数过大请稍后重试");
                socket.close();
                continue;
            }
            System.out.println("connected from " + socket.getRemoteSocketAddress());
            executor.submit(new Handler(socket));
        }
    }
}


class Handler implements Runnable{
    Socket socket;
    private long time = System.currentTimeMillis()/1000;

    public Handler(Socket socket){
       this.socket = socket;
    }

    @Override
    public void run(){
        try {
            InputStream input = socket.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
            while(true){
                String str = bufferedReader.readLine();
                if (str != null) {
                    System.out.println(str);
                    BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    bufferedWriter.write("收到消息:" + str);
                    bufferedWriter.newLine();
                    bufferedWriter.flush();
                    time = System.currentTimeMillis()/1000;
                }
                long nowTime = System.currentTimeMillis()/1000;
                if((nowTime - time)>10){
                    socket.close();
                    break;
                }
            }
        }catch (IOException e) {
            System.out.println(e.getMessage());
            throw new RuntimeException(e);
        }
    }

}
